package com.bst.etl.batch.tasklet;

import com.bst.common.exception.base.BaseException;
import com.bst.system.framework.datasource.DynamicDataSource;
import com.bst.system.framework.utils.DBUtil;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

@Component("delDmSQLExecTasklet")
@StepScope
public class DelDmSQLExecTasklet implements Tasklet {
    @Value("#{jobParameters[idDbTar]}")
    String idDbTar;
    @Value("#{jobParameters[delSql]}")
    String delSql;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        DataSource dwDataSource = DynamicDataSource.getDataSourceById(idDbTar);
        if (dwDataSource == null) throw new BaseException(String.format("数据源获取失败！"));

        if (StringUtils.isEmpty(this.getSQL())) return RepeatStatus.FINISHED;

        if (StringUtils.isEmpty(this.getSQL()) && this.getSQL().trim().length() <= 6) return RepeatStatus.FINISHED;

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = dwDataSource.getConnection();
            Statement statement = connection.createStatement();
            statement.execute(delSql);
        } catch (Exception e) {
            e.printStackTrace();
            BaseException baseException = new BaseException("执行SQL错误! SQL语句为:" + delSql);
            throw baseException;
        } finally {
            DBUtil.closeDBResources(null, preparedStatement, connection);
        }

        return RepeatStatus.FINISHED;
    }


    protected String getSQL() {
        return this.delSql;
    }
}